/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package fc.ejb;

import fc.entity.FcUser;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.jboss.logging.Logger;

/**
 *
 * @author Admin
 */
@Stateless
public class DukeBdBean {

    private static final Logger logger = Logger.getLogger("fc.ejb.DukeBdBean");
    @PersistenceContext
    private EntityManager entityManager;

    public Double getAvgAgeDiff() {
        Double ageDiff = (Double) entityManager.createNamedQuery("findAvg").getSingleResult();
        logger.info("AVG age diff is: " + ageDiff);
        return ageDiff;
    }

    public int getAgeDiff(Date date) {
        int ageDifference;

        Calendar theirBirthday = new GregorianCalendar();
        Calendar dukesBirthday = new GregorianCalendar(1995, Calendar.MAY, 23);

        // Set the Calendar object to the passed in Date
        theirBirthday.setTime(date);

        // Subtract the user's age from Duke's age
        ageDifference = dukesBirthday.get(Calendar.YEAR)
                - theirBirthday.get(Calendar.YEAR);
        logger.info("Raw ageDifference is: " + ageDifference);
        // Check to see if Duke's birthday occurs before the user's. If so,
        // subtract one from the age difference
        if (dukesBirthday.before(theirBirthday) && (ageDifference > 0)) {
            ageDifference--;
        }

        FcUser user = new FcUser(date, ageDifference);
        entityManager.persist(user);

        logger.info("Final ageDiff is: " + ageDifference);
        return ageDifference;

    }
}
